package de.recipeminer.persistence;

import com.db4o.Db4oEmbedded;
import com.db4o.ObjectContainer;
import de.recipeminer.tools.Config;
import org.apache.log4j.Logger;

import java.io.File;

public class Db4oController {
    private static Logger logger = Logger.getLogger(Db4oController.class);
    private static Db4oController instance = new Db4oController();
    private static String PRODUCTION_DB_FILE = "recipeminer_test.db4o";
    private static String TEST_DB_FILE = "recipeminer_production.db4o";
    private ObjectContainer productionObjectContainer = null;
    private ObjectContainer testObjectContainer = null;

    private Db4oController() {
        Config config = Config.getInstance();
    }

    public static Db4oController getInstance() {
        return instance;
    }

    public ObjectContainer getProductionObjectContainer() {
        if (productionObjectContainer == null) {
            File db4oProduction = Config.getInstance().getResource(PRODUCTION_DB_FILE);
            logger.info(String.format("Opening Db4o Production Database in %s...", db4oProduction.toString()));
            productionObjectContainer = Db4oEmbedded.openFile(db4oProduction.toString());
        }
        return productionObjectContainer;
    }

    public ObjectContainer getTestObjectContainer() {
        if (testObjectContainer == null) {
            File db4oTest = Config.getInstance().getResource(TEST_DB_FILE);
            logger.info(String.format("Opening Db4o Test Database in %s...", db4oTest.toString()));
            testObjectContainer = Db4oEmbedded.openFile(db4oTest.toString());
        }
        return testObjectContainer;
    }

    public void releaseProductionObjectContainer() {
        if (productionObjectContainer != null) {
            productionObjectContainer.close();
            productionObjectContainer = null;
        }
    }

    public void releaseTestObjectContainer() {
        if (testObjectContainer != null) {
            testObjectContainer.close();
            testObjectContainer = null;
        }
    }
}
